package com.work.task.ssh;

import ch.ethz.ssh2.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class SSHOperator {

    private static final Logger logger = LoggerFactory.getLogger(SSHOperator.class);

    /** 超时时间 */
    //private static final int TIME_OUT = 1000 * 5 * 60;
    private static final int TIME_OUT = 1000 * 30;



    /**
     * 其他服务器下载文件
     * @param config                  服务连接配置
     * @param remoteFile              服务器上的文件名
     * @param remoteTargetDirectory   服务器上文件的所在路径
     * @param newPath                 下载文件的路径
     */
    public static void  downloadFile(SSHConfig config,String remoteFile, String remoteTargetDirectory,String newPath){


           try {
               if (config == null || !config.isAvailable()){
                   return;
               }
               SSHConnect sshConnect = new SSHConnect(config);

                if(sshConnect.isConnected()){
                   logger.info("spc [" + remoteFile + "] from " + sshConnect.getConfig().getHost() + " to "
                           + newPath);
                   Connection conn = sshConnect.getConnection();

                    SCPClient client = new SCPClient(conn);
                    SCPInputStream sis = client.get(remoteTargetDirectory + "/" + remoteFile);
                    File f = new File(newPath);
                    if(!f.exists()){
                        f.mkdirs();
                    }
                    File newFile = new File(newPath + remoteFile);
                    FileOutputStream fos = new FileOutputStream(newFile);
                    byte[] b = new byte[4096];
                    int i;
                    while ((i = sis.read(b)) != -1){
                        fos.write(b,0, i);
                        logger.info("i={}",i);
                    }
                    fos.flush();
                    fos.close();
                    sis.close();
                    sshConnect.close();
                    logger.info("download ok");

               }

           }catch (IOException ex){
               ex.printStackTrace();
           }


    }

    /**
     * (上传文件到服务器)将文件拷贝到其他计算机上
     * @param uploadFilePath (本地文件)
     * @param remoteDir
     * @throws IOException
     */
    public static boolean uploadFile(SSHConfig config,String uploadFilePath, String remoteDir)  {

        try {
            if (config == null || !config.isAvailable()){
                return false;
            }
            SSHConnect sshConnect = new SSHConnect(config);

            if(sshConnect.isConnected()){
                logger.info("spc [" + uploadFilePath + "] to " + sshConnect.getConfig().getHost() + remoteDir);
                Connection conn = sshConnect.getConnection();
                File f = new File(uploadFilePath);

                SCPClient client = new SCPClient(conn);
                SCPOutputStream os = client.put(f.getName(),f.length(), remoteDir,null);
                byte[] b = new byte[4096];
                FileInputStream fis = new FileInputStream(f);
                int i;
                while ((i = fis.read(b)) != -1) {
                    os.write(b, 0, i);
                }
                os.flush();
                fis.close();
                os.close();
                sshConnect.close();
                //conn.close();
                logger.info("upload ok");
                return true;
            }


        }catch (IOException ex){
            ex.printStackTrace();
        }
        return false;

    }

    //执行本地的cmd命令.(DOS命令)
    public  int runLocal(String cmd) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("running local cmd [" + cmd + "]");
        }
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec(cmd);
        InputStream stdout = new StreamGobbler(p.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
            if (logger.isDebugEnabled()) {
                logger.debug(line);
            }
        }
        return p.exitValue();
    }

    /**
     * 执行一个命令
     *   ShellResult status = operator.exec("python /home/wulanzhou/test.py");
     *   或者
     *   ShellResult status = operator.exec("ifconfig");
     *
     * @param scripts  需要执行的脚本路径或者脚本内容
     * @return ShellResult类
     * @throws Exception
     */
    public static ShellResult exec(SSHConfig config,String scripts) {

        if (config == null || !config.isAvailable()){
            return null;
        }
        SSHConnect sshConnect = new SSHConnect(config);

        try {
            if(sshConnect.isConnected()){

                Charset charset = StandardCharsets.US_ASCII;

                Connection connection = sshConnect.getConnection();
                Session session = connection.openSession();

                InputStream stdOut = new StreamGobbler(session.getStdout());
                InputStream stdErr = new StreamGobbler(session.getStderr());
                // Execute a command on the remote machine.
                session.execCommand(scripts);
                String outStr = processStream(stdOut, charset.name());
                String outErr = processStream(stdErr, charset.name());
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
                int exitStatus = session.getExitStatus();
                sshConnect.close();
                return new ShellResult(outStr, outErr, exitStatus);

            }
        }catch (IOException ex){
            ex.printStackTrace();
        }

       return null;
    }

    public static ShellResult uploadFileWithExec(SSHConfig config,String localPath) {

        ShellResult status = exec(config,"pwd");
        if (status!=null && !StringUtils.isEmpty(status.getResult())){
            String rootDir = status.getResult();
            if (!rootDir.endsWith("/")){
                rootDir += "/";
            }
            logger.info("服务器根目录:{}",rootDir);
            //上传文件
            boolean success = uploadFile(config,localPath,rootDir);
            //执行命令
            if (success){
                logger.info("上传本地文件成功");
                File tempFile =new File(localPath);
                List<String> cmdList = new ArrayList<>();
                cmdList.add("chmod -R 777 "+rootDir+tempFile.getName()); //添加权限
                cmdList.add("sh "+rootDir+tempFile.getName()); //执行命令
                cmdList.add("rm -rf "+rootDir+tempFile.getName()); //删除命令
                ShellResult rs= exec(config,String.join(";",cmdList));
                return rs;
            }else{
                logger.info("上传本地文件失败");
            }

        }
        return null;
    }


    /**
     * 执行脚本
     *
     * @param in      输入流
     * @param charset 字符编码
     * @return
     * @throws IOException
     */
    private static String processStream(InputStream in, String charset) throws IOException {
        //byte[] buf = new byte[1024];

        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        while ((len = in.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        /**
        while (in.read(buf) != -1) {
            sb.append(new String(buf, charset));
        }
         **/
        StringBuilder sb = new StringBuilder();
        sb.append(new String(outSteam.toByteArray(),"utf-8"));
        return sb.toString();
    }
}
